package com.zh.tea.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import com.github.pagehelper.PageInfo;
import com.zh.tea.entity.News;
import com.zh.tea.entity.Tea;
import com.zh.tea.service.NewsService;
import com.zh.tea.service.TeaService;
import com.zh.tea.service.impl.NewsServiceImpl;
import com.zh.tea.service.impl.TeaServiceImpl;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class NewsServlet
 */
@WebServlet("/NewsServlet")
public class NewsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public NewsServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		NewsService newsService = new NewsServiceImpl();
		String opt = request.getParameter("opt");
		if("page".equals(opt)) {
			String pageindex = request.getParameter("pageindex");
			Integer pagenum = pageindex == null ? 1 : Integer.parseInt(pageindex);
			Integer pagesize = 4;
			PageInfo<News> pageinfo = newsService.getNews(null, pagenum, pagesize);
			session.setAttribute("pageinfo", pageinfo);
			request.getRequestDispatcher("newsCentre.jsp").forward(request, response);
		}else if("detailNews".equals(opt)) {
			String nid = request.getParameter("nid");
			News news = newsService.getOneNews(Integer.parseInt(nid));
			session.setAttribute("news", news);
			request.getRequestDispatcher("softpd.jsp").forward(request, response);
		}else if ("showAll".equals(opt)) {

			int currentNumber = Integer.parseInt(request.getParameter("page") == null ? "1" : request.getParameter("page"));// 页码
			String currentPage = request.getParameter("limit") == null ? "10" : request.getParameter("limit");// 大小

			PageInfo<News> paget = newsService.getNews(null, currentNumber, Integer.parseInt(currentPage));

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("code", 0);
			jsonObject.put("msg", "");
			jsonObject.put("count", paget.getTotal());
			jsonObject.put("data", paget.getList());

			String json = jsonObject.toString();
			out.print(json);
			
		}else if ("delete".equals(opt)) {
			String id = request.getParameter("nid");
			if(id!=null && !"".equals(id)) {
				int a = newsService.deleteNews(Integer.parseInt(id));
				if(a>0) {
					out.print("<script>alert('删除成功!');location.href='/tea/admin/NewsUpdateAndDelete.jsp'</script>");
				}else {
					out.print("<script>alert('删除失败!');location.href='/tea/admin/NewsUpdateAndDelete.jsp'</script>");
				}
			}
		}else if ("update".equals(opt)) {
			String id = null;
			String title = null;
			String author = null;
			String pic1 = null;
			String page1 = null;
			String pic2 = null;
			String page2 = null;
			String pic3 = null;
			String page3 = null;
			String date = null;
			String teano = null;
			boolean flag = true;
			String file1 = null;
			String fileName1 = null;
			String file2 = null;
			String fileName2 = null;
			String file3 = null;
			String fileName3 = null;
			News news = new News();
			FileItemFactory factory=new DiskFileItemFactory();
			//创建input框分析器
			ServletFileUpload fileUpload=new ServletFileUpload(factory);
			//分析request请求
			try {
				List<FileItem> list=fileUpload.parseRequest(request);
				for(FileItem item:list){
					if(item.isFormField()){//普通表单字段
						if("id".equals(item.getFieldName())){
							id=item.getString("utf-8");		
						}else if("title".equals(item.getFieldName())){
							title=item.getString("utf-8");
						}else if("author".equals(item.getFieldName())){
							author=item.getString("utf-8");
						}else if("page1".equals(item.getFieldName())){
							page1=item.getString("utf-8");
						}else if("page2".equals(item.getFieldName())){
							page2=item.getString("utf-8");
						}else if("page3".equals(item.getFieldName())){
							page3=item.getString("utf-8");
						}else if("date".equals(item.getFieldName())){
							date=item.getString("utf-8");
						}else if("teano".equals(item.getFieldName())){
							teano=item.getString("utf-8");
						}
					}else {//文件表单字段
						String ext1=null;
						String ext2=null;
						String ext3=null;
						File upfile1=null;
						File upfile2=null;
						File upfile3=null;
						String[] exts = { "jpg", "doc", "css", "gif" };

						List es = Arrays.asList(exts);
						if("pic1".equals(item.getFieldName())){
							
								file1 = item.getName();
								if(!"".equals(file1) && file1!=null) {
								ext1 = FilenameUtils.getExtension(file1);
								String realPath = request.getServletContext().getRealPath("/newsImages");// 项目真实路径
								fileName1 = FilenameUtils.getBaseName(file1) + System.currentTimeMillis() + "."
										+ FilenameUtils.getExtension(file1);
								upfile1 = new File(realPath, fileName1);
								if (es.contains(ext1)) {
									item.write(upfile1);
									news.setPic1("newsImages\\" + fileName1);
								} else {
								
									flag = false;
								}
							}
							
							
						}else if("pic2".equals(item.getFieldName())){
							
								file2 = item.getName();
								if(!"".equals(file2) && file2!=null) {
								 ext2 = FilenameUtils.getExtension(file2);
								String realPath = request.getServletContext().getRealPath("/newsImages");// 项目真实路径
								fileName2 = FilenameUtils.getBaseName(file2) + System.currentTimeMillis() + "."
										+ FilenameUtils.getExtension(file2);
								upfile2 = new File(realPath, fileName2);
								
								if (es.contains(ext2)) {
									item.write(upfile2);
									news.setPic2("newsImages\\" + fileName2);
								} else {
									
									flag = false;
								}
							}
							
						}else if("pic3".equals(item.getFieldName())){
							
								file3 = item.getName();
								if(!"".equals(file3) && file3!=null) {
								 ext3 = FilenameUtils.getExtension(file3);
								String realPath = request.getServletContext().getRealPath("/newsImages");// 项目真实路径
								fileName3 = FilenameUtils.getBaseName(file3) + System.currentTimeMillis() + "."
										+ FilenameUtils.getExtension(file3);
								 upfile3 = new File(realPath, fileName3);
								 if (es.contains(ext3)) {
										item.write(upfile3);
										news.setPic3("newsImages\\" + fileName3);
									} else {
										
										flag = false;
									}
							}
							
						}
					}
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(flag) {
				if(!"".equals(id)) {
					news.setNid(Integer.parseInt(id));
				}
				news.setTitle(title);
				news.setAuthor(author);
				news.setPage1(page1);
				news.setPage2(page2);
				news.setPage3(page3);
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date date1 = null;
				if(!"".equals(date) && date!=null) {
					try {
						date1 = sdf.parse(date);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				news.setDate(date1);
				news.setTeano(teano);
				int i = newsService.updateNews(news);
				if(i>0) {
					out.print("<script>alert('修改成功!');location.href='/tea/admin/NewsUpdateAndDelete.jsp'</script>");
				}else {
					out.print("<script>alert('修改失败!');location.href='/tea/admin/NewsUpdateAndDelete.jsp'</script>");
				}
			}else {
				out.print("<script>alert('不允许此文件类型上传！修改失败！');location.href='/tea/admin/NewsUpdateAndDelete.jsp';</script>");
			}
				
			
		}else if("add".equals(opt)){
			String title = null;
			String author = null;
			String pic1 = null;
			String page1 =null;
			String pic2 = null;
			String page2 = null;
			String pic3 =null;
			String page3 =null;
			String date = null;
			String teano = null;
			
			String file1 = null;
			String fileName1 = null;
			String file2 = null;
			String fileName2 = null;
			String file3 = null;
			String fileName3 = null;
			boolean flag = true;// 文件是否上传成功
			News news = new News();
			Date time = new Date();
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			//新建一个FileItrm的工厂类分析input标签
			FileItemFactory factory=new DiskFileItemFactory();
			//创建input框分析器
			ServletFileUpload fileUpload=new ServletFileUpload(factory);
			//分析request请求
			try {
				List<FileItem> list=fileUpload.parseRequest(request);
				for(FileItem item:list){
					if(item.isFormField()){//普通表单字段
						if("title".equals(item.getFieldName())){
							title=item.getString("utf-8");
						}else if("author".equals(item.getFieldName())){
							author=item.getString("utf-8");
						}else if("page1".equals(item.getFieldName())){
							page1=item.getString("utf-8");
						}else if("page2".equals(item.getFieldName())){
							page2=item.getString("utf-8");
						}else if("page3".equals(item.getFieldName())){
							page3=item.getString("utf-8");
						}else if("date".equals(item.getFieldName())){
							date=item.getString("utf-8");
						}else if("teano".equals(item.getFieldName())){
							teano=item.getString("utf-8");
						}
					}else {//文件表单字段
			
						String ext1=null;
						String ext2=null;
						String ext3=null;
						File upfile1=null;
						File upfile2=null;
						File upfile3=null;
						String[] exts = { "jpg", "doc", "css", "gif" };

						List es = Arrays.asList(exts);
						if("pic1".equals(item.getFieldName())){
							
								file1 = item.getName();
							if(!"".equals(file1) && file1!=null) {
								 ext1 = FilenameUtils.getExtension(file1);
								String realPath = request.getServletContext().getRealPath("/newsImages");// 项目真实路径
								fileName1 = FilenameUtils.getBaseName(file1) + System.currentTimeMillis() + "."
										+ FilenameUtils.getExtension(file1);
								upfile1 = new File(realPath, fileName1);
								if (es.contains(ext1)) {
									
									item.write(upfile1);
									news.setPic1("newsImages\\" + fileName1);
								} else {
									
									flag = false;
								}
							}
							
							
						}else if("pic2".equals(item.getFieldName())){
							
								file2 = item.getName();
								if(!"".equals(file2) && file2!=null) {
								 ext2 = FilenameUtils.getExtension(file2);
								String realPath = request.getServletContext().getRealPath("/newsImages");// 项目真实路径
								fileName2 = FilenameUtils.getBaseName(file2) + System.currentTimeMillis() + "."
										+ FilenameUtils.getExtension(file2);
								upfile2 = new File(realPath, fileName2);
								
								if (es.contains(ext2)) {
									item.write(upfile2);
									news.setPic2("newsImages\\" + fileName2);
								} else {
									
									flag = false;
								}
							}
							
						}else if("pic3".equals(item.getFieldName())){
							
								file3 = item.getName();
								if(!"".equals(file3) && file3!=null) {
								 ext3 = FilenameUtils.getExtension(file3);
								String realPath = request.getServletContext().getRealPath("/newsImages");// 项目真实路径
								fileName3 = FilenameUtils.getBaseName(file3) + System.currentTimeMillis() + "."
										+ FilenameUtils.getExtension(file3);
								upfile3 = new File(realPath, fileName3);
								
								if (es.contains(ext3)) {
									item.write(upfile3);
									news.setPic3("newsImages\\" + fileName3);
								} else {
									
									flag = false;
								}
							}
							
						}
					}
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (flag) {
				
				news.setTitle(title);
				news.setAuthor(author);
				news.setPage1(page1);
				news.setPage2(page2);
				news.setPage3(page3);
				news.setTeano(teano);
				if(!"".equals(date) && date!=null) {
					try {
						news.setDate(df.parse(date));
					} catch (ParseException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				
				try {
					news.setDate(df.parse(date));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				int i = newsService.addNews(news);
				if (i > 0) {
					out.print("<script>alert('添加成功！');location.href='/tea/admin/NewsUpdateAndDelete.jsp';</script>");
				}else {
					out.print("<script>alert('添加失败!');location.href='/tea/admin/NewsUpdateAndDelete.jsp'</script>");
				}
			}else {
				out.print("<script>alert('不允许此文件类型上传！添加失败！');location.href='/tea/admin/NewsUpdateAndDelete.jsp';</script>");
			}
		}else if ("sel".equals(opt)){
			TeaService ts = new TeaServiceImpl();
			PageInfo<Tea> p = ts.getTea(null, 0, 0);
			List<Tea> list = p.getList();
			session.setAttribute("list2", list);
			out.print("<script>location.href='/tea/admin/NewsInsert.jsp'</script>");
		}else if ("sel1".equals(opt)){
			TeaService ts = new TeaServiceImpl();
			PageInfo<Tea> p = ts.getTea(null, 0, 0);
			List<Tea> list = p.getList();
			session.setAttribute("list3", list);
			out.print("<script>location.href='/tea/admin/UpdateNews.jsp'</script>");
		}else if("sel2".equals(opt)) {
			String nid = request.getParameter("nid");
			NewsService ns = new NewsServiceImpl();
			News new1 = ns.getOneNews(Integer.parseInt(nid));
			session.setAttribute("new1", new1);
			out.print("<script>location.href='/tea/admin/UpdateNews.jsp'</script>");
		}

		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
